package com.zl.learning.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOClient {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(6666));
        while (!socketChannel.finishConnect()) {
            System.out.println("wait");
        }
        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
        new Thread(() -> {
            while (true) {
                try {
                    int count = selector.select();
                    if (count > 0) {
                        Set<SelectionKey> keys = selector.selectedKeys();
                        for (Iterator<SelectionKey> iterator = keys.iterator(); iterator.hasNext(); ) {
                            SelectionKey selectionKey = iterator.next();
                            if (selectionKey.isReadable()) {
                                SocketChannel channel = (SocketChannel) selectionKey.channel();
                                ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                                byteBuffer.clear();
                                channel.read(byteBuffer);
                                byteBuffer.flip();
                                System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
                            }
                            iterator.remove();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        String str;
        while (!"exit".equals(str = scanner.nextLine())) {
            socketChannel.write(ByteBuffer.wrap(str.getBytes()));
        }
    }
}
